/*
 * @ author madman 
 * @ uploadFile   上传类
 */
import fs from 'fs';
const config = require('../../config/config');
const _qiniuUpload = require("./qiniu");
const Busboy = require('busboy')
const path = require('path');
const Utils = require('../controllers/utils');
const _Upload = require("../models/upload/upload.model");
const globalConfig = config[process.env.NODE_ENV || 'development'];

class UploadController {
    // 本地上传
    static _upload(ctx, options) {
        return new Promise((resolve, reject) => {
            let upload = {}
            const _Busboy = new Busboy({headers: ctx.req.headers})
            const filePath = path.join(options.path, '')
            const confirm = Utils.mkdirsSync(filePath)
            if (!confirm) {
              return
            }
            _Busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
               const fileFormat = filename.split(".");
               const fileName = Date.now() + "." + fileFormat[fileFormat.length - 1]   // 重命名上传文件
               const saveTo = path.join(path.join(filePath, fileName))
               file.pipe(fs.createWriteStream(saveTo))
               upload.fileName = fileName
              })
            _Busboy.on('field', function (data,val) {
               upload[data] = val
            })
            _Busboy.on('finish', function (data) {
               resolve(upload)
            })
            _Busboy.on('error', function (err) {
               console.log('err...')
            })
            ctx.req.pipe(_Busboy)
        })
    }
    // 七牛云上传
    static qiniu(ctx, serverPath) {
        return new Promise((resolve, reject) => {
            fs.existsSync(serverPath, function(isexit){
                if (!isexit) {
                    return ctx.error({ msg: '上传文件时发生错误!' });
                }
            });
            _qiniuUpload.qiniuPrameter(serverPath).then(result =>{
                if (!result || !result.url) {
                    return ctx.error({ msg: '上传到云端时发生错误!' });
                }
                if (result) {
                    let fileName = path.win32.basename(serverPath);
                    resolve({
                       fileName: fileName || '',
                       url: result.url
                    })
                    fs.unlinkSync(serverPath);
                }
            });
        })
    }
    // 图片上传
    async uploadFile(ctx, next) {
        const serverPath = path.join(__dirname, '../../public/uploads/')
        var _SYS = await Utils.getPrameter()  // 获取系统参数
        if(!_SYS){
            return ctx.error({ msg: '获取不到系统参数!' });
        }else{
           // 本地图片流返回数据  
           const _upload = await UploadController._upload(ctx, {
             path: serverPath,
             type: _SYS.setup.upload_type
           })
           const imgPath = path.join(serverPath,_upload.fileName);
           // 获取系统参数配置upload_type
           if (_SYS.setup.upload_type === '2') {
             const result = await _qiniuUpload.qiniuPrameter(imgPath)
             if (!result || !result.url) {
                return ctx.error({ msg: '上传到云端时发生错误!' });
             }
             //上传到七牛云后返回结果替换_upload字段
             if (result) {
                let fileName = path.win32.basename(imgPath);
                _upload.fileName = fileName
                _upload.url = result.url
             }
           }
           // 根据图片mid查找是否有此图片
           let Result = await _Upload.findOne({ "_id": _upload.mid })
           if (!Result) {
              ctx.upload = { mid: '', files: [], file: '' };
              // await next()
           }
           // 处理图片的URL
           var url = _SYS.setup.upload_type === '1' ? _SYS.setup.serverUrl + '/uploads/' + _upload.fileName : _upload.url
           let _files = {
               imgPath: []
            }
            // 判断图片流传过来的参数是否是传单张图片,单张将数组清空
            if (Result && !_upload.isMultiSelect) {
                Result.imgPath = []
            } 
            // 如果图片流传过来的参数有mid就执行更新操作
            if (typeof(_upload.mid) !== "undefined") {
                var files = {
                        "name": _upload.fileName,
                        "url": url + (_upload.imageMogr || '')
                    }
                if (_upload.isMultiSelect !== 'true') {
                    Result.imgPath = [files]
                } else {
                    Result.imgPath.push(files)
                }
                let data = await Result.save()
                if (data) {
                    // 挂载在ctx, 传递给下个中间件
                    ctx.upload = {
                        mid: data._id,
                        files: data.imgPath,                  //多图数组
                        file: url + (_upload.imageMogr || '') //单个图片
                    };
                }
            } else {
                _files.imgPath.push({
                    "name": _upload.fileName,
                    "url": url + (_upload.imageMogr || '')
                })
                let Upload = new _Upload(_files)
                let data = await Upload.save()
                if (data) {
                    // 挂载在ctx, 传递给下个中间件
                    ctx.upload = {
                        mid: data._id,
                        files: data.imgPath,                  //多图数组
                        file: url + (_upload.imageMogr || '')  //单个图片
                    };
                }
            }
           if (_SYS.setup.upload_type === '2') {
               // 同步到七牛云后删除此图片
               fs.unlinkSync(imgPath); 
           }
           console.log()
           await next()
        }
    }

}

export default new UploadController;